<template>
  <div class="app-container">





    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.gen_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用模型" prop="modelName">
        <el-select v-model="queryParams.modelName" placeholder="请选择使用模型" clearable>
          <el-option
            v-for="dict in dict.type.gpt_model"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-row :gutter="10" class="mb8" style="margin-bottom: 23px;">
      <el-divider content-position="left">生成配置</el-divider>
      <el-col :span="1.5" style="line-height: 2;">
        <el-switch
          v-model="useClassswitch"
          active-text=""
          inactive-text="是否根据已有分类信息">
        </el-switch>
      </el-col>


      <el-col :span="1.5">
        分类项
        <el-select v-model="itemId" ref="optionItemRef"  placeholder="请选择分类项">
          <el-option
            v-for="item in classItemOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-col>

      <el-col :span="1.5">
        使用模型
        <el-select v-model="model_conf" placeholder="请选择使用模型" clearable>
          <el-option
            v-for="dict in dict.type.gpt_model"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-col>


    </el-row>



    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:classify:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:classify:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:classify:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="openImportTable">
          导入待分类内容</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:classify:export']"
        >导出</el-button>
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="multiple"
          @click="genTask"
        >批量生成勾选</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-dropdown icon="el-icon-refresh"  size="mini" split-button type="primary"  @click="genTaskAll">
          生成当前查询下所有
          <el-dropdown-menu slot="dropdown">
            <span style="margin-left: 10px">指定数量：</span>
            <el-input-number v-model="gennum" controls-position="right" @change="handleSelectChange" :min="0" :max="9999999"></el-input-number>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>

      <el-col :span="1.5">
        <el-dropdown  size="mini" @command="checkClick">
          <el-button type="primary" size="mini" :disabled="checkClassmultiple"  @click="checkNames">
            检查{{this.selectNames}}<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>

          <el-dropdown-menu slot="dropdown" >
            <el-dropdown-item v-for="item in classItemOptions" :key="item.name" :command="item.id" >{{item.name}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classifyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类编号" align="center" prop="id" />
      <el-table-column label="文本内容" align="center" width="350"  prop="txtContent" />
      <el-table-column label="分类信息" align="center" width="150" prop="classNames" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gen_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用模型" width="150" align="center" prop="modelName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gpt_model" :value="scope.row.modelName"/>
        </template>
      </el-table-column>
      <el-table-column label="花费token" align="center" prop="useToken" />
      <el-table-column label="操作" align="center"  width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            :loading="scope.row.genTaskLoading"
            @click="genTask(scope.row)"
          >生成</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:classify:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:classify:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改内容分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文本源id" prop="txtId">
          <el-input v-model="form.txtId" placeholder="请输入文本源id" />
        </el-form-item>
        <el-form-item label="文本内容">
          <editor v-model="form.txtContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="文本长度" prop="txtLength">
          <el-input v-model="form.txtLength" placeholder="请输入文本长度" />
        </el-form-item>
        <el-form-item label="分类id" prop="classIds">
          <el-input v-model="form.classIds" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="分类名称" prop="classNames">
          <el-input v-model="form.classNames" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.gen_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用模型" prop="modelName">
          <el-select v-model="form.modelName" placeholder="请选择使用模型">
            <el-option
              v-for="dict in dict.type.gpt_model"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="花费token" prop="useToken">
          <el-input v-model="form.useToken" placeholder="请输入花费token" />
        </el-form-item>
        <el-form-item label="token日志id" prop="useTokenId">
          <el-input v-model="form.useTokenId" placeholder="请输入token日志id" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 导入数据包 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="900px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx"
        :headers="upload.headers"
        :action="upload.url+ '?prompts='+form.demandPrompts +
        '&useModel='+form.useModel "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-row>

                <el-form-item label="默认算法模型"  prop="useModel">
                  <el-select
                    v-model="form.useModel"
                    placeholder="使用模型"
                    clearable
                  >
                    <el-option
                      v-for="dict in dict.type.gpt_model"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>

                <el-col :span="24">
                  <el-form-item label="内容领域">
                    <el-input v-model="form.demandPrompts" type="textarea" placeholder="输入领域有助于AI理解" />
                  </el-form-item>
                </el-col>


              </el-row>
            </el-form>

          </div>
          <span>仅允许导入xls格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载包模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import { startGenAll,classItemSelect,listClassify, getClassify, delClassify, addClassify, updateClassify,startGen,checkTxtClassifyName } from "@/api/article/classify";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Classify",
  dicts: ['gpt_model', 'gen_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      useClassswitch:false,
      itemId:null,
      modelName:null,
      model_conf:null,
      classItemOptions:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      checkClassmultiple:true,
      selectNames:"分类",
      selectItemId:null,
      genTaskLoading:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      gennum:0,
      // 内容分类表格数据
      classifyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "上传数据包",
        useModel:'',

        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        demandPrompts:null,
        useModel:'',
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/article/classify/importData"
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        gennum:0,
        txtContent: null,
        classNames: null,
        status: "0",
        modelName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    classItemSelect().then(response => {
      this.classItemOptions = response.rows;
      console.log(response)
    });
  },
  methods: {
    /** 查询内容分类列表 */
    getList() {
      this.loading = true;
      listClassify(this.queryParams).then(response => {
        this.classifyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    checkClick(command){
      console.log(command)
      let selName = "";
      let selId = "";
      for(var item in this.classItemOptions){
        console.log(item)
           if(this.classItemOptions[item].id==command){
              console.log(this.classItemOptions[item])
               selName = "["+this.classItemOptions[item].name+"]";
               selId = this.classItemOptions[item].id;
                break;
           }
      }
      this.selectNames = selName;
      this.selectItemId = selId;
      this.$message('您选择了数据项为： ' + selName);
      this.checkClassmultiple = false;
    },
    checkNames(){
      console.log(this.selectItemId );
      let genPs = {
        itemId:this.selectItemId
      }
      checkTxtClassifyName(genPs).then(response => {
        console.log(response);
        this.$modal.msgSuccess("操作成功！");
      });

    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        txtId: null,
        txtContent: null,
        txtLength: null,
        classIds: null,
        classNames: null,
        createBy: null,
        gennum:0,
        status: "0",
        createTime: null,
        updateTime: null,
        modelName: null,
        useToken: null,
        useTokenId: null
      };
      this.resetForm("form");
    },
    handleSelectChange(value){
      console.log(value);
      this.gennum = value;
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      // this.$refs.import.show();
      this.reset();
      this.upload.title = "待分类内容上传";
      this.upload.open = true;
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
      this.$download.zip("/common/download?fileName=temp.xlsx&delete=false" , "temp.xlsx");

    },
    //执行生成
    genTask(row){
      const ids = row.id || this.ids;
      this.$set(row, 'genTaskLoading', true);

      let genPs = {
        useClassswitch:this.useClassswitch,
        itemId:this.itemId,
        model_conf:this.model_conf
      }

      this.$modal.confirm('是否确认生成主题文章编号为"' + ids + '"的数据项？').then(function() {
        return startGen(ids,genPs);
      }).then(() => {
        this.activeName= 'all';
        this.getList();
        this.$set(row, 'genTaskLoading', false);
        this.$modal.msgSuccess("操作成功！");
      }).catch(() => {
        this.$set(row, 'genTaskLoading', false);
      });
    },


    genTaskAll(){
      // startGenAll
      console.log(typeof this.queryParams);
      let genps = this.queryParams;
      console.log(genps)
      genps.gennum = this.gennum;
      genps.status = genps.status==null?"0":genps.status.toString();
      genps.useClassswitch = this.useClassswitch,
      genps.itemId = this.itemId,
      genps.model_conf = this.model_conf

      console.log(genps)
      this.$modal.confirm('确定执行任务吗？').then(function() {
        return startGenAll(genps);
      }).then(() => {
        this.$modal.msgSuccess("任务提交成功");
        this.activeName= 'all';
        this.queryParams.status = null;
        this.getList();
      }).catch(() => {
      });



    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加内容分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClassify(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改内容分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClassify(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClassify(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除内容分类编号为"' + ids + '"的数据项？').then(function() {
        return delClassify(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/classify/export', {
        ...this.queryParams
      }, `classify_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
